import { Button, Modal, Descriptions, message } from 'antd'
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react'

import { FCTable } from '@components'
import DetailAdd from './DetailAdd'
import { UserAuthConfigDeatilColumns as detailColumns } from './tableDetailColumns'
import { useMainContext } from '@contexts/MainContext'
import '../styles/UserAuthConfig.less'

const Detail = ({ userRoleInfo, roleDataList, visible = false, onOk, onCancel, detailRef }) => {
  const { isButtomShow } = useMainContext()

  const detailAddRef = useRef('userAuthDetail')
  const [addVisible, setAddVisible] = useState(false)

  //机构tree勾选数据
  // const [checkData, setCheckData] = useState([]) 树
  const [unitCodes, setUnitCodes] = useState([])

  //表格数据
  const [dataList, setDataList] = useState([])
  // const [rowData, setRowData] = useState({}) 树

  // roleId 新增无主键，修改有
  const [roleId, setRoleId] = useState()

  //新增角色机构事件--> 弹窗
  const onAdd = () => {
    setRoleId(null)
    setUnitCodes([])
    detailAddRef.current.setUnitLabel('')
    // setCheckData([]) 树
    setAddVisible(true)
  }

  //新增角色机构事件 --> 弹窗取消
  const onAddCancel = () => {
    setAddVisible(false)
  }

  //暴露给主页面 用于重新渲染表格
  useImperativeHandle(detailRef, () => ({
    setDataList: (data) => setDataList(data),
    setUnitData: (data) => detailAddRef.current.setUnitData(data),
  }))

  //删除角色机构事件
  const onDelete = (record) => {
    Modal.confirm({
      title: '系统提示',
      cancelText: '取消',
      okText: '确定',
      content: `确定要删除角色名称（${record.roleName}），机构名称（${record.authUnitNameStr}）这条数据吗？`,
      onOk: () => {
        setDataList(dataList?.filter((item) => item.roleId !== record.roleId))
      },
    })
  }

  //主页面过来加载已有权限的数据
  useEffect(() => {
    if (userRoleInfo) {
      setDataList(userRoleInfo.userRoleList)
    }
  }, [userRoleInfo])

  //新增角色机构事件 --> 保存
  const onAddOk = (data) => {
    const { roleId, authUnitCodeList } = data

    if (!(roleId && authUnitCodeList.length)) {
      Modal.info({
        title: '系统提示',
        okText: '确定',
        content: `配置人员权限时 "角色权限" 、"机构权限" 都是必填项`,
      })
    } else {
      const authUnitNameStr = detailAddRef.current.getUnitLabel()
      if (roleId) {
        // 修改
        const list = [{
          roleId: roleId,
          roleName: roleDataList.find((i) => i.roleId === roleId).roleName,
          authUnitCodeList: authUnitCodeList,
          // authUnitCodeList: unitCodes,
          authUnitCodeStr: authUnitCodeList.join(),
          // authUnitNameStr: authUnitNameStr ? authUnitNameStr.join() : rowData.authUnitNameStr, 树
          authUnitNameStr: authUnitNameStr,
        }]

        // 刷新一下表格
        setDataList([...list])

      } else {
        //新增

        const list = [{
          roleId: roleId,
          roleName: roleDataList.find((i) => i.roleId === roleId).roleName,
          authUnitCodeList: authUnitCodeList,
          // authUnitCodeList: unitCodes,
          authUnitCodeStr: authUnitCodeList.join(),
          // authUnitNameStr: authUnitNameStr.join(), 树
          authUnitNameStr: authUnitNameStr,
        }]

        // 刷新一下表格
        setDataList([...list])
      }

      setAddVisible(false)
    }
  }

  const onEdit = (e) => {
    // const newAuthUnitCode = e.authUnitCodeStr?.split(',')
    // setCheckData(newAuthUnitCode) 树
    setUnitCodes(e.authUnitCodeList)
    detailAddRef.current.setUnitLabel(e.authUnitNameStr)
    setRoleId(e.roleId)
    // setRowData(e) 树
    setAddVisible(true)
  }

  const fixedProps = {
    title: '人员权限列表',
    columns: [...detailColumns],
    actionColumn: {
      // 定制操作栏的内容
      title: '操作',
      elements: [
        isButtomShow('630103') && {
          type: 'button',
          text: '编辑',
          onClick: onEdit,
        },
        isButtomShow('630105') &&{
          type: 'button',
          text: '删除',
          onClick: onDelete,
        },
      ],
    },
    rowKey: 'roleId',
    // scroll: { x: null, y: 500 },
    pagination: false,
  }
  return (
    <>
      <Modal
        title="人员权限配置"
        className="user-auth-config"
        centered
        open={visible}
        width={800}
        cancelText={'取消'}
        okText={'保存'}
        onOk={() => onOk({ userCode: userRoleInfo.userCode, dataList })}
        onCancel={onCancel}
        maskClosable= {false}
      >
        <Descriptions column={2}>
          <Descriptions.Item label="姓名">{userRoleInfo.userName}</Descriptions.Item>
          <Descriptions.Item label="工号">{userRoleInfo.userCode}</Descriptions.Item>
          <Descriptions.Item label="员工机构">{userRoleInfo.unitName}</Descriptions.Item>
        </Descriptions>
        <br />
        <FCTable {...fixedProps} dataSource={dataList} />
        <br />
        {isButtomShow('630102') && (!dataList?.length) ? <Button onClick={onAdd}> 新增 </Button> : null}
      </Modal>

      <DetailAdd
        detailRef={detailAddRef}
        // userRolData={userRoleInfo}
        userCode={userRoleInfo.userCode}
        // userRolData={dataList}
        // userRolData={{ userCode: userRoleInfo.userCode }}
        roleDataList={roleDataList}
        addVisible={addVisible}
        onAddOk={onAddOk}
        onAddCancel={onAddCancel}
        roleId={roleId}
        setRoleId={setRoleId}
        unitCodes={unitCodes}
        setUnitCodes={setUnitCodes}
        // checkData={checkData} 树
      />
    </>
  )
}
export default Detail
